package com.mxy.myapplication2.java;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/12/25.
 *
 * @author 马晓勇
 */

public abstract class Util {

    private static Toast toast;

    /**
     * 线程池 使用内部类加载机制创建，使用时再初始化,线程安全
     */
    private static class MyExecutorService {

        private static ExecutorService executorService
                = new ThreadPoolExecutor(5,
                10,
                1,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(512));
    }

    /**
     * @return 线程池
     */
    public static ExecutorService getExecutorService() {
        return MyExecutorService.executorService;
    }

    /**
     * 解决Toast连击长时间不消失
     *
     * @param context
     * @param content
     */
    public static void showToast(Context context, String content) {
        if (toast == null) {
            toast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
        } else {
            toast.setText(content);
        }
        toast.show();
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dipValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue,
                context.getResources().getDisplayMetrics());
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / density + 0.5f);
    }


    /**
     * 获取当前屏幕实际宽和高（单位px）
     *
     * @param activity
     * @return
     */
    public static DisplayMetrics getDisplay(Activity activity) {
        DisplayMetrics metrics = activity.getResources().getDisplayMetrics();
        return metrics;
        //设备独立像素 与 屏幕实际像素
        //1.屏幕密度（dpi=density）不同，决定了屏幕的实际像素也不同,所以用像素设置控件大小，在不同密度的屏幕上，展示效果会出现偏差
        //2.于是谷歌提出了设备独立像素，Density-independent pixel（即dip或dp），1dip=屏幕密度为160的屏幕的1像素
        //3.我们在程序中设置控件的大小，应当使用设备独立像素，程序在运行之后，会自动进行转换，
        //转换公式为:控件在屏幕上显示的实际像素=设备独立像素（程序员手动设置）*（当前屏幕密度/160）;
    }

    /**
     * @param activity
     * @return 屏幕高度(包含状态栏 / 不包括导航栏)
     */
    public static int getScreenHeight(Activity activity) {
        DisplayMetrics metrics = activity.getResources().getDisplayMetrics();
        return metrics.heightPixels;
    }


    /**
     * @param activity
     * @return 状态栏高度
     */
    public static int getStatusBarHeight(Activity activity) {
        int result = 0;
        int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = activity.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * @param application
     * @return 获取manifests中定义的metaData值 例如接口地址，例如渠道号等
     */
    public static String getAppMetaData(Application application, String metaKey) {
        try {
            PackageManager pm = application.getPackageManager();
            ApplicationInfo appInfo = pm.getApplicationInfo(application.getPackageName(),
                    PackageManager.GET_META_DATA);
            return appInfo.metaData.getString(metaKey);
        } catch (PackageManager.NameNotFoundException ignored) {
            return "";
        }
    }


    /**
     * 获取ip地址
     *
     * @return
     */
    public static String getIpAddress() {

        String hostIp = null;
        try {
            //需要申请android.permission.INTERNET权限
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return hostIp;
    }


    /**
     * 判断service是否存活
     *
     * @param context
     * @param className
     * @return
     */
    public static boolean isServiceExisted(Context context, String className) {
        ActivityManager activityManager =
                (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (activityManager != null) {
            List<ActivityManager.RunningServiceInfo> serviceList =
                    activityManager.getRunningServices(Integer.MAX_VALUE);
            if (serviceList.size() <= 0) {
                return false;
            }
            for (int i = 0; i < serviceList.size(); i++) {
                ActivityManager.RunningServiceInfo serviceInfo = serviceList.get(i);
                ComponentName serviceName = serviceInfo.service;
                if (serviceName.getClassName().equals(className)) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 将输入流读出并转换为字符串，专门给Socket使用
     * 当时不关闭流，输入输出流统一关闭
     *
     * @return
     * @throws IOException
     */
    public static String convertStreamToStringUtf8(Socket client) throws IOException {
        StringBuilder sb = new StringBuilder();
        String line = null;

        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream(),
                    "UTF-8"));

            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //读取完毕，单方面关闭输入流 此时不能使用close，一旦调用，Socket就会关闭
        //必须等待输入输出流都处理完毕后，统一关闭Sokcet
        client.shutdownInput();
        return sb.toString();
    }
}